package models

import (
	"context"
	"fmt"
	"time"
	_ "time"

	"go-papers/cache"
	orm "go-papers/database"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"golang.org/x/crypto/bcrypt"
)

type MomInfo struct {
	MemberId  int    `json:"memberId" gorm:"type:int(11) unsigned;primary_key"` // 会员id / 社区达人id
	MomStatus string `json:"momStatus" gorm:"type:tinyint(1);"`                 // 社区达人 管家妈妈状态  1 审核中   3 不通过  5 驳回
	MomReason string `json:"momReason" gorm:"type:string(255);"`                // 审核原因 等
	IsMom     int    `json:"isMom" gorm:"type:tinyint(1);"`                     // 是否管家妈妈  2 是 ，默认 1
}
type MemberRegisterInfo struct {
	MemberId    int    `json:"memberId" gorm:"type:int(11) unsigned;primary_key"` //
	MemberCode  string `json:"memberCode" gorm:"type:varchar(64);"`               // 会员邀请码
	NickName    string `json:"nickName" gorm:"type:varchar(64);"`                 // 昵称
	RealName    string `json:"realName" gorm:"type:varchar(64);"`                 // 真实姓名 达人姓名
	AccountName string `json:"accountName" gorm:"type:varchar(255);"`             // 账户 登录账号
	Password    string `json:"password" gorm:"type:varchar(128);"`                // 密码
	Phone       string `json:"phone" gorm:"type:varchar(128);"`                   // 手机号
	WxOpenid    string `json:"wxOpenid" gorm:"type:varchar(255);"`                // 微信openid
	WxUnionid   string `json:"wxUnionid" gorm:"type:varchar(255);"`               // 微信公共id

	RegisterTime string `json:"registerTime" gorm:"type:datetime;"`   //注册时间
	ActiveTime   string `json:"activeTime" gorm:"type:varchar(255);"` //活跃时间
	CreatedAt    string `json:"createdAt" gorm:"type:datetime;"`      //活跃时间
}

type MomRegisterInfo struct {
	MemberId    int    `json:"memberId" gorm:"type:int(11) unsigned;primary_key"` //
	MemberCode  string `json:"memberCode" gorm:"type:varchar(64);"`               // 会员邀请码
	NickName    string `json:"nickName" gorm:"type:varchar(64);"`                 // 昵称
	RealName    string `json:"realName" gorm:"type:varchar(64);"`                 // 真实姓名 达人姓名
	AccountName string `json:"accountName" gorm:"type:varchar(255);"`             // 账户 登录账号
	Password    string `json:"password" gorm:"type:varchar(128);"`                // 密码
	Phone       string `json:"phone" gorm:"type:varchar(128);"`                   // 手机号
	WxOpenid    string `json:"wxOpenid" gorm:"type:varchar(255);"`                // 微信openid
	WxUnionid   string `json:"wxUnionid" gorm:"type:varchar(255);"`               // 微信公共id

	RegisterTime string `json:"registerTime" gorm:"type:datetime;"`   //注册时间
	ActiveTime   string `json:"activeTime" gorm:"type:varchar(255);"` //活跃时间
	CreatedAt    string `json:"createdAt" gorm:"type:datetime;"`      //活跃时间

	MomStatus     string `json:"momStatus" gorm:"type:tinyint(1);"` // 默认 "1"
	CardNo        string `json:"cardNo" gorm:"type:varchar(128);"`  // 身份证号
	Province      string `json:"province" gorm:"type:varchar(64);"` // 省份
	City          string `json:"city" gorm:"type:varchar(64);"`     // 城市
	Area          string `json:"area" gorm:"type:varchar(128);"`    // 区域
	Address       string `json:"address" gorm:"type:varchar(255);"` // 地址
	AddressText   string `json:"addressText" gorm:"type:text;"`     // 地址
	AddressSearch string `json:"addressSearch" gorm:"type:text;"`   // 地址
}

type Member struct {
	MemberId      int    `json:"memberId" gorm:"type:int(11) unsigned;primary_key"` //
	NickName      string `json:"nickName" gorm:"type:varchar(64);"`                 // 昵称
	MemberCode    string `json:"memberCode" gorm:"type:varchar(64);"`               // 会员邀请码
	RealName      string `json:"realName" gorm:"type:varchar(64);"`                 // 真实姓名 达人姓名
	AccountName   string `json:"accountName" gorm:"type:varchar(255);"`             // 账户 登录账号
	Cover         string `json:"cover" gorm:"type:varchar(255);"`                   // 头像地址
	Password      string `json:"password" gorm:"type:varchar(128);"`                // 密码
	Phone         string `json:"phone" gorm:"type:varchar(128);"`                   // 手机号
	CardNo        string `json:"cardNo" gorm:"type:varchar(128);"`                  // 身份证号
	Province      string `json:"province" gorm:"type:varchar(64);"`                 // 省份
	City          string `json:"city" gorm:"type:varchar(64);"`                     // 城市
	Area          string `json:"area" gorm:"type:varchar(128);"`                    // 区域
	Address       string `json:"address" gorm:"type:varchar(255);"`                 // 地址
	AddressText   string `json:"addressText" gorm:"type:text"`                      // 地址 json 自负
	AddressSearch string `json:"addressSearch" gorm:"type:text"`                    // 地址 json 自负

	TotalOrderNums int     `json:"total_order_nums" gorm:"type:int(11);"`  // 累计订单数
	TotalPrice     float64 `json:"total_price" gorm:"type:decimal(10,2);"` // 累计订单金额

	WxOpenid     string `json:"wxOpenid" gorm:"type:varchar(255);"`     // 微信openid
	WxUnionid    string `json:"wxUnionid" gorm:"type:varchar(255);"`    // 微信公共id
	RegisterTime string `json:"registerTime" gorm:"type:varchar(255);"` //注册时间
	ActiveTime   string `json:"activeTime" gorm:"type:varchar(255);"`   //活跃时间
	UpdateTime   string `json:"updateTime" gorm:"type:datetime;"`       //更新时间
	CreateBy     string `json:"createBy" gorm:"type:varchar(255);"`     // 创建人 id
	UpdateBy     string `json:"updateBy" gorm:"type:varchar(255);"`     // 更新人 id

	//管家妈妈属性
	MomStatus   string `json:"momStatus" gorm:"type:tinyint(1);"`     // 社区达人 管家妈妈状态  1 审核中   3 不通过  5 驳回
	MomReason   string `json:"momReason" gorm:"type:string(255);"`    // 审核原因 等
	IsMom       int    `json:"isMom" gorm:"type:tinyint(1);"`         // 是否管家妈妈  2 是 ，默认 1
	MomUserId   int    `json:"momUserId" gorm:"type:int(11);"`        // 关联的 社区达人id
	MomUserCode string `json:"momUserCode" gorm:"type:varchar(255);"` // 关联的 社区达人code
	MomRealName string `json:"momRealName" gorm:"type:varchar(255);"` // 社区达人 真实姓名

	// ------- 字表 ----//
	MomAge        string `json:"momAge" gorm:"type:varchar(255);"`        // 达人年龄
	MomLevel      string `json:"momLevel" gorm:"type:varchar(255);"`      // 佣金级别
	MomOrgan      string `json:"momOrgan" gorm:"type:varchar(255);"`      // 签约机构数
	MomCustomer   string `json:"momCustomer" gorm:"type:varchar(255);"`   // 客户数
	MomNewer      string `json:"momNewer" gorm:"type:varchar(255);"`      // 社区达人拓展数
	ApprovalTime  string `json:"approvalTime" gorm:"type:varchar(255);"`  // 申请时间
	SuccessTime   string `json:"successTime" gorm:"type:varchar(255);"`   // 成功时间
	MomCommission string `json:"momCommission" gorm:"type:varchar(255);"` // 达人总佣金

	ApprovalTimeStart string `json:"-" gorm:"-"` // 申请跟新 起始时间
	ApprovalTimeEnd   string `json:"-" gorm:"-"` // 申请跟新 结束时间
	SuccessTimeStart  string `json:"-" gorm:"-"` // 通过跟新 起始时间
	SuccessTimeEnd    string `json:"-" gorm:"-"` // 通过跟新 结束时间
	KeyWord           string `json:"-" gorm:"-"` // 通过跟新 结束时间

	ThirdUserInfo interface{} `json:"thirdUserInfo" `
	DataScope     string      `json:"dataScope" gorm:"-"`
	Params        string      `json:"params"  gorm:"-"`
	Token         string      `json:"token"  gorm:"-"`
	BaseModel
}

type MemberSearch struct {
	MemberId      int    `json:"memberId" gorm:"type:int(11) unsigned;primary_key"` //
	NickName      string `json:"nickName" gorm:"type:varchar(64);"`                 // 昵称
	MemberCode    string `json:"memberCode" gorm:"type:varchar(64);"`               // 会员邀请码
	Cover         string `json:"cover" gorm:"type:varchar(255);"`                   // 头像地址
	Password      string `json:"password" gorm:"type:varchar(128);"`                // 密码
	Phone         string `json:"phone" gorm:"type:varchar(128);"`                   // 手机号
	Province      string `json:"province" gorm:"type:varchar(64);"`                 // 省份
	City          string `json:"city" gorm:"type:varchar(64);"`                     // 城市
	Area          string `json:"area" gorm:"type:varchar(128);"`                    // 区域
	Address       string `json:"address" gorm:"type:varchar(255);"`                 // 地址
	AddressSearch string `json:"addressSearch" gorm:"type:text"`                    // 地址 json 自负
	RegisterTime  string `json:"registerTime" gorm:"varchar(255);"`                 //注册时间
}

func (Member) TableName() string {
	return "member"
}

// RegisterMom
func (e *Member) RegisterMom(m *MomRegisterInfo, mid int) (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	noeTime := time.Now().Format("2006-01-02 15:04:05")

	//查询是否存在
	if err := table.Where("member_id = ?", mid).First(&doc).Error; err == nil {
		//参数1:是要修改的数据
		m.AddressSearch = m.Province + "/" + m.City + "/" + m.Area + "/" + m.Address
		//参数2:是修改的数据
		if err = orm.Eloquent.Table(e.TableName()).Model(&doc).Updates(&m).Error; err != nil {
			lognew.Error(context.TODO(), "ErrorUpdate", lognew.Fields{"m": m, "err": err.Error()})
			return doc, err
		}
		mid = doc.MemberId
	} else {
		m.MemberCode = tools.GetMemberCode()
		m.NickName = m.RealName
		m.RegisterTime = noeTime
		m.ActiveTime = noeTime
		m.CreatedAt = noeTime
		m.AddressSearch = m.Province + "/" + m.City + "/" + m.Area + "/" + m.Address
		result := table.Create(m)
		if result.Error != nil {
			err := result.Error
			lognew.Error(context.TODO(), "ErrorCreate", lognew.Fields{"m": m, "err": err.Error()})
			return doc, err
		}
		mid = m.MemberId
		doc.MemberId = m.MemberId
		doc, _ = e.Get()
	}

	lognew.Info(context.TODO(), "memberInfo", lognew.Fields{"doc": doc, "mid": mid})

	// 第二张表数据 插入或者更新
	var mm MemberMom
	mm.MemberId = mid
	info, err := mm.Get()
	if err != nil {
		//插入
		mm.ApprovalTime = noeTime
		mm.MomPhone = m.Phone
		mm.MomLevel = "0" // RegisterMom
		_, err = mm.Create()
		if err != nil {
			lognew.Error(context.TODO(), "ErrorInsert", lognew.Fields{"m": m, "err": err.Error()})
		}

	} else {
		info.ApprovalTime = noeTime
		info.MomLevel = "0" // RegisterMom
		info.MomPhone = m.Phone
		_, err = info.Update(info.MemberMomId)
		if err != nil {
			lognew.Error(context.TODO(), "ErrorUpdate", lognew.Fields{"m": m, "err": err.Error()})
		}
	}

	if err := table.Where("member_id = ?", mid).First(&doc).Error; err != nil {

		lognew.Error(context.TODO(), "ErrorUpdate", lognew.Fields{"m": m, "err": err.Error()})

		return doc, err
	}

	return doc, nil
}

// Register
func (e *Member) Register(m MemberRegisterInfo) (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	result := table.Create(&m)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}

	if err := table.Where("member_id = ?", m.MemberId).First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 创建Member
func (e *Member) Create() (Member, error) {
	var doc Member
	result := orm.Eloquent.Table(e.TableName()).Create(&e)
	if result.Error != nil {
		err := result.Error
		return doc, err
	}
	doc = *e
	return doc, nil
}

//加密
func (e *Member) Encrypt() (err error) {
	if e.Password == "" {
		return
	}

	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
		return
	} else {
		e.Password = string(hash)
		return
	}
}

func (e *Member) GetEncrypt(pwd string) (pp string) {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		pp = ""
	} else {
		pp = string(hash)
	}
	return
}

func (e *Member) GetByCode(code string) (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_code = ?", code)

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

//UpdateMom
func (e *Member) UpdateMom(id int, momId int) (bool, error) {
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_id = ?", id)
	err := table.Update("mom_user_id", momId).Error
	return true, err
}

func (e *Member) UpdatePwd(id int, pwd string) (bool, error) {
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_id = ?", id)
	pp := e.GetEncrypt(pwd)
	err := table.Update("password", pp).Error
	return true, err
}

func (e *Member) GetByID(id int) (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_id = ?", id)

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

//GetMomPhone
func (e *Member) GetMomPhone(id int) string {

	//cache 读取 然后返回
	cacheKey := fmt.Sprintf("member:mom:phone:%d", id)
	if foo, ok := cache.GoLocalCache.Get(cacheKey); ok {
		l, _ := foo.(string)
		return l
	}

	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_id = ?", id)

	if err := table.First(&doc).Error; err != nil {
		return ""
	}
	ll := doc.Phone
	// 写入cache
	cache.GoLocalCache.Set(cacheKey, ll, 30*time.Minute)

	return ll
}

//GetMomName
func (e *Member) GetMomName(id int) string {

	//cache 读取 然后返回
	cacheKey := fmt.Sprintf("member:mom:%d", id)
	if foo, ok := cache.GoLocalCache.Get(cacheKey); ok {
		l, _ := foo.(string)
		return l
	}

	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("member_id = ?", id)

	if err := table.First(&doc).Error; err != nil {
		return ""
	}
	ll := doc.NickName
	if doc.RealName != "" {
		ll = doc.RealName
	}

	// 写入cache
	cache.GoLocalCache.Set(cacheKey, ll, 30*time.Minute)

	return ll
}

// GetPulpleNums
func (e *Member) GetPulpleNums(id int) int {
	var count = 0
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("mom_user_id  = ?", id)
	table.Count(&count)
	return count
}

// GetByAccountName
func (e *Member) GetByAccountName(name string) (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("account_name = ?", name)
	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}
	return doc, nil
}

// 获取Member
func (e *Member) Get() (Member, error) {
	var doc Member
	table := orm.Eloquent.Table(e.TableName())
	if e.MemberId != 0 {
		table = table.Where("member_id = ?", e.MemberId)
	}
	if e.NickName != "" {
		table = table.Where("nick_name like ?", "%"+e.NickName+"%")
	}
	if e.RealName != "" {
		table = table.Where("real_name like ?", "%"+e.RealName+"%")
	}
	if e.AccountName != "" {
		table = table.Where("account_name like ?", "%"+e.AccountName+"%")
	}
	if e.Password != "" {
		table = table.Where("password = ?", e.Password)
	}
	if e.Phone != "" {
		table = table.Where("phone like ?", "%"+e.Phone+"%")
	}
	if e.CardNo != "" {
		table = table.Where("card_no like ?", "%"+e.CardNo+"%")
	}
	if e.Province != "" {
		table = table.Where("province = ?", e.Province)
	}
	if e.City != "" {
		table = table.Where("city = ?", e.City)
	}
	if e.Area != "" {
		table = table.Where("area = ?", e.Area)
	}
	if e.Address != "" {
		table = table.Where("address like ?", "%"+e.Address+"%")
	}
	if e.AddressText != "" {
		table = table.Where("address_text like ?", "%"+e.AddressText+"%")
	}
	if e.AddressSearch != "" {
		table = table.Where("address_search like ?", "%"+e.AddressSearch+"%")
	}
	if e.IsMom != 0 {
		table = table.Where("is_mom = ?", e.IsMom)
	}
	if e.MomUserId != 0 {
		table = table.Where("mom_user_id = ?", e.MomUserId)
	}
	if e.WxOpenid != "" {
		table = table.Where("wx_openid = ?", e.WxOpenid)
	}
	if e.WxUnionid != "" {
		table = table.Where("wx_unionid = ?", e.WxUnionid)
	}
	if e.UpdateBy != "" {
		table = table.Where("update_by = ?", e.UpdateBy)
	}

	if err := table.First(&doc).Error; err != nil {
		return doc, err
	}

	if doc.MomUserId != 0 {
		doc.MomRealName = e.GetMomName(doc.MomUserId)
	}
	return doc, nil
}

// 获取Member带分页
func (e *Member) GetMomPage(pageSize int, pageIndex int) ([]Member, int, error) {
	var doc []Member

	table := orm.Eloquent.Select(" `member`.* ,m.mom_age,m.mom_level,m.mom_organ,m.mom_customer,m.mom_newer,f.real_name as mom_real_name,m.approval_time ,m.success_time ,m.mom_commission").Table(e.TableName())
	table = table.Joins("left join `member_mom` as m on m.member_id = member.member_id ")
	table = table.Joins("left join  `member` as f on f.member_id = member.mom_user_id ")
	if e.MemberId != 0 {
		table = table.Where("member.member_id = ?", e.MemberId)
	}
	if e.NickName != "" {
		table = table.Where("member.nick_name like ?", "%"+e.NickName+"%")
	}
	if e.RealName != "" {
		table = table.Where("member.real_name like ?", "%"+e.RealName+"%")
	}
	if e.AccountName != "" {
		table = table.Where("member.account_name like ?", "%"+e.AccountName+"%")
	}
	if e.Phone != "" {
		table = table.Where("member.phone like ?", "%"+e.Phone+"%")
	}
	if e.CardNo != "" {
		table = table.Where("member.card_no like ?", "%"+e.CardNo+"%")
	}
	if e.Province != "" {
		table = table.Where("member.province like ?", "%"+e.Province+"%")
	}
	if e.City != "" {
		table = table.Where("member.city like ?", "%"+e.City+"%")
	}
	if e.Area != "" {
		table = table.Where("member.area like ?", "%"+e.Area+"%")
	}
	if e.AddressText != "" {
		table = table.Where("member.address_text like ?", "%"+e.AddressText+"%")
	}
	if e.AddressSearch != "" {
		table = table.Where("member.address_search like ?", "%"+e.AddressSearch+"%")
	}
	if e.Address != "" {
		table = table.Where("member.address like ?", "%"+e.Address+"%")
	}
	if e.MomStatus != "" {
		table = table.Where("member.mom_status = ?", e.MomStatus)
	} else {
		table = table.Where("member.mom_status > ?", 0)
	}

	if e.MomUserId != 0 {
		table = table.Where("member.mom_user_id = ?", e.MomUserId)
	}
	if e.WxOpenid != "" {
		table = table.Where("member.wx_openid = ?", e.WxOpenid)
	}
	if e.WxUnionid != "" {
		table = table.Where("member.wx_unionid = ?", e.WxUnionid)
	}

	if e.SuccessTimeStart != "" {
		table = table.Where("m.success_time >= ?", e.SuccessTimeStart)
	}
	if e.SuccessTimeEnd != "" {
		table = table.Where("m.success_time <= ?", e.SuccessTimeEnd)
	}

	if e.ApprovalTimeStart != "" {
		table = table.Where("m.approval_time >= ?", e.ApprovalTimeStart)
	}
	if e.ApprovalTimeEnd != "" {
		table = table.Where("m.approval_time <= ?", e.ApprovalTimeEnd)
	}

	if e.UpdateBy != "" {
		table = table.Where("member.update_by = ?", e.UpdateBy)
	}

	// 数据权限控制(如果不需要数据权限请将此处去掉)
	dataPermission := new(DataPermission)
	dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	table, err := dataPermission.GetDataScope(e.TableName(), table)
	if err != nil {
		return nil, 0, err
	}
	var count int

	if err := table.Order(" `member`.`member_id` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("member.deleted_at IS NULL").Count(&count)
	return doc, count, nil
}

func (e *Member) GetCountByMom(momid int) (int, int) {

	var count int
	var count1 int
	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("mom_user_id = ?", momid)
	table.Where(" deleted_at IS NULL").Count(&count)

	//
	table1 := orm.Eloquent.Table(e.TableName())
	table1 = table1.Where("mom_user_id = ?", momid)
	table1 = table1.Where("is_mom = 2")
	table1.Where(" deleted_at IS NULL").Count(&count1)

	return count, count1
}

// GetPageSearch
func (e *Member) GetPageSearch(pageSize int, pageIndex int) ([]MemberSearch, int, error) {
	var doc []MemberSearch

	table := orm.Eloquent.Select(" `member`.* ").Table(e.TableName())
	table = table.Joins("left join  `member` as f on f.member_id = `member`.mom_user_id ")
	if e.MemberId != 0 {
		table = table.Where(" `member`.member_id = ?", e.MemberId)
	}
	if e.KeyWord != "" {
		table = table.Where(" member.nick_name like ? OR member.phone like ? OR member.member_id like ? ", "%"+e.KeyWord+"%", "%"+e.KeyWord+"%", "%"+e.KeyWord+"%")
	}
	if e.NickName != "" {
		table = table.Where("member.nick_name like ?", "%"+e.NickName+"%")
	}
	if e.RealName != "" {
		table = table.Where("member.real_name like ?", "%"+e.RealName+"%")
	}
	if e.AccountName != "" {
		table = table.Where("member.account_name like ?", "%"+e.AccountName+"%")
	}
	if e.Phone != "" {
		table = table.Where("member.phone like ?", "%"+e.Phone+"%")
	}
	if e.Province != "" {
		table = table.Where("member.province like ?", "%"+e.Province+"%")
	}
	if e.City != "" {
		table = table.Where("member.city like ?", "%"+e.City+"%")
	}
	if e.Area != "" {
		table = table.Where("member.area like ?", "%"+e.Area+"%")
	}
	if e.Address != "" {
		table = table.Where("member.address like ?", "%"+e.Address+"%")
	}
	if e.AddressSearch != "" {
		table = table.Where("member.address_search like ?", "%"+e.AddressSearch+"%")
	}
	if e.AddressText != "" {
		table = table.Where("( member.province like ? OR member.city like ? OR member.area like ? )", "%"+e.AddressText+"%", "%"+e.AddressText+"%", "%"+e.AddressText+"%")
	}
	if e.IsMom != 0 {
		table = table.Where("member.is_mom = ?", e.IsMom)
	}
	if e.MomUserId != 0 {
		table = table.Where("member.mom_user_id = ?", e.MomUserId)
	}

	var count int

	if err := table.Order(" `member`.`member_id` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("member.deleted_at IS NULL").Count(&count)
	return doc, count, nil
}

// 获取Member带分页
func (e *Member) GetPage(pageSize int, pageIndex int) ([]Member, int, error) {
	var doc []Member

	table := orm.Eloquent.Select(" `member`.*,f.real_name as mom_real_name").Table(e.TableName())
	table = table.Joins("left join  `member` as f on f.member_id = member.mom_user_id ")
	if e.MemberId != 0 {
		table = table.Where("member.member_id = ?", e.MemberId)
	}
	if e.NickName != "" {
		table = table.Where("member.nick_name like ?", "%"+e.NickName+"%")
	}
	if e.RealName != "" {
		table = table.Where("member.real_name like ?", "%"+e.RealName+"%")
	}
	if e.AccountName != "" {
		table = table.Where("member.account_name like ?", "%"+e.AccountName+"%")
	}
	if e.Phone != "" {
		table = table.Where("member.phone like ?", "%"+e.Phone+"%")
	}
	if e.CardNo != "" {
		table = table.Where("member.card_no like ?", "%"+e.CardNo+"%")
	}
	if e.Province != "" {
		table = table.Where("member.province like ?", "%"+e.Province+"%")
	}
	if e.City != "" {
		table = table.Where("member.city like ?", "%"+e.City+"%")
	}
	if e.Area != "" {
		table = table.Where("member.area like ?", "%"+e.Area+"%")
	}
	if e.Address != "" {
		table = table.Where("member.address like ?", "%"+e.Address+"%")
	}
	if e.AddressSearch != "" {
		table = table.Where("member.address_search like ?", "%"+e.AddressSearch+"%")
	}
	if e.AddressText != "" {
		table = table.Where("( member.province like ? OR member.city like ? OR member.area like ? )", "%"+e.AddressText+"%", "%"+e.AddressText+"%", "%"+e.AddressText+"%")
	}
	if e.IsMom != 0 {
		table = table.Where("member.is_mom = ?", e.IsMom)
	}
	if e.MomUserId != 0 {
		table = table.Where("member.mom_user_id = ?", e.MomUserId)
	}
	if e.WxOpenid != "" {
		table = table.Where("member.wx_openid = ?", e.WxOpenid)
	}
	if e.WxUnionid != "" {
		table = table.Where("member.wx_unionid = ?", e.WxUnionid)
	}
	if e.RegisterTime != "" {
		table = table.Where("member.register_time >= ?", e.RegisterTime)
	}
	if e.UpdateBy != "" {
		table = table.Where("member.update_by = ?", e.UpdateBy)
	}

	// 数据权限控制(如果不需要数据权限请将此处去掉)
	dataPermission := new(DataPermission)
	dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	table, err := dataPermission.GetDataScope(e.TableName(), table)
	if err != nil {
		return nil, 0, err
	}
	var count int

	if err := table.Order(" `member`.`member_id` DESC", true).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("member.deleted_at IS NULL").Count(&count)
	return doc, count, nil
}

// 更新Member
func (e *Member) Update(id int) (update Member, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("member_id = ?", id).First(&update).Error; err != nil {
		return
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

// 删除Member
func (e *Member) Delete(id int) (success bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("member_id = ?", id).Delete(&Member{}).Error; err != nil {
		success = false
		return
	}
	success = true
	return
}

//批量删除
func (e *Member) BatchDelete(id []int) (Result bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("member_id in (?)", id).Delete(&Member{}).Error; err != nil {
		return
	}
	Result = true
	return
}
